<?php
/**
@mo add 2017年5月2日 10:09:53
该类主要用于判断当前商品在满足促销的条件是否可以加入购物车
 */

class b2c_checkproduct_check {

  
/*
@mo add
 
    根据productId返回good_id
*/
    public function get_good_id($product_id)
    {
        if(empty($product_id))
            return -1;
      $pre_rule = app::get('b2c')->model('products');
        $filter_c = array('product_id'=>$product_id);
        $goods_ids = $pre_rule->getList('goods_id', $filter_c, 0, -1, 'goods_id ASC');
        return $goods_ids;
    }

/*
    @mo  获取当前 所有的满足促销，筛选符合的优惠条件
 */
    public function get_gift_of_full_promotion($goods_id)
    {
        $promotions  = array();
        //根据促销条件
        $pre_rule = app::get('b2c')->model('sales_rule_order');
        $is_statue = "true";
        $filter_c = array('status|nequal'=>$is_statue);//bug 缺少时间判断  @mo 获取当前时间在促销规则之内的促销规则
        $promotions = $pre_rule->getList('rule_id,name,conditions,member_lv_ids,office_ids,from_time,to_time,action_conditions', $filter_c, 0, -1, 'rule_id ASC');
        $promotions_temp = $promotions;
        
    	//test hzk

    	
        if(!empty($promotions))
        {
            foreach ($promotions as $key => $value) {

              //add by lkb 如果结束时间过期，就不满足促销活动
                if($value['to_time']<time())
                {
                    unset($promotions_temp[$key]);//把不符合的规则释放
                }
                //add end
               if($value['conditions']['conditions'][0]['type2'] != app::get('b2c')->_('Fullofgifts'))
               {
                    unset($promotions_temp[$key]);//把不符合的规则释放
               }
            }
            
    	//test hzk
    	//var_dump('<br>55555<br>');
            return $this->get_current_promotion($promotions_temp,$goods_id);
        }
    	
        return array();  
    }
    /*
        //符合当前商品的促销条件（满赠促销的规则）
     */
    public function get_current_promotion($promotions,$goods_id)
    {

        if(empty($promotions))
            return array();
       $promotions_temp = $promotions;

      //add by lkb 获取会员ID\
       $member_id=kernel::single('b2c_user_object')->get_member_id();
       $userObjects = kernel::single('b2c_user_object');
       $member_lv_id=($userObjects->get_member_lv($member_id));

       // var_dump($member_lv_id);
       //add end
       // var_dump($promotions_temp);
        foreach ($promotions as $key => $value) {
           $member_lv_ids = explode(',',$value["member_lv_ids"]);

           //如果存在多个商品进行满赠
           if(count($value['action_conditions']["conditions"][0]["value"]))
           {
           $goods_ids = $value['action_conditions']["conditions"][0]["value"];
          // var_dump(in_array($member_lv_id, $value["member_lv_ids"]);
            if(!in_array($goods_id, $goods_ids)||!in_array($member_lv_id, $member_lv_ids))
            {
                unset($promotions_temp[$key]);//把不符合的规则释放
            }
          }
          else
          {
            if($value['conditions']['conditions'][0]['conditions'][0]['value'] != $goods_id
              ||!in_array($member_lv_id, $member_lv_ids))
             
            {
                unset($promotions_temp[$key]);//把不符合的规则释放
            }
          }

            unset($member_lv_ids);
            unset($goods_ids);
        }

//                          echo '<pre>';
//             var_dump($promotions_temp)ss;
//             echo '======vvddd==vvv======ii';
        //2017年5月9日 13:41:05 //用于判断用户登录，会员等级，办事处，是否存在一个不符合
//         var_dump($promotions);
// var_dump(22222222222222);
        // var_dump($promotions_temp);

        //modified by lkb 2017-06-04
        // var_dump($goods_id);
        // var_dump(1111111111111111111111111111);
        // var_dump($promotions_temp);
        $can =  $this->get_max_goods($promotions_temp);
        // $can =  $this->get_max_goods($promotions);

        //modified end 
      
      if(!$can) return array();

        return $promotions_temp;
        
    }
//add by hzk 06-02 copy from ctl product.php
    /*
     *获取商品促销数据
     * */
    function _get_goods_promotion($goodsId){
    	$userObject = kernel::single('b2c_user_object');
    	if(!($userObject->is_login())){
    	  $nologindata = array();
    		return $nologindata;
    	}
        $siteMember = $userObject->get_current_member();
        $member_lv_id = (!empty($siteMember['member_lv'])) ? $siteMember['member_lv'] : '0';
        
        $goodsPromotion = kernel::single('b2c_goods_object')->get_goods_promotion($goodsId,'1');
//                echo '<pre>';
//        var_dump($goodsId);
//                echo '<br>';
//        var_dump($goodsPromotion);
//        exit;
        $productPromotion = array();
        $giftId = array();
        //商品促销
        if( $goodsPromotion['goods'] ){
            foreach($goodsPromotion['goods'] as $row){
                if(strpos($row['apply_platform'],'1') === false){
                    continue;
                }
                $temp = is_array($row['action_solution']) ? $row['action_solution'] : @unserialize($row['action_solution']);
                if(key($temp) == 'gift_promotion_solutions_gift'){
                    if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                        continue;
                    }
                    $giftId = array_merge($giftId,$temp['gift_promotion_solutions_gift']['gain_gift']);
                    continue;
                }

                if(isset($same_rule[key($temp)]) && $same_rule[key($temp)]){
                    continue;
                }else{
                    $same_rule[key($temp)] = true;
                }
                $ruleData = app::get('b2c')->model('sales_rule_goods')->getList('*',array('rule_id'=>$row['rule_id']));
                $productPromotion['goods'][$row['rule_id']]['action_solution'] = $ruleData[0]['action_solution'];

                $productPromotion['goods'][$row['rule_id']]['name'] = $ruleData[0]['name'];
                $productTag = kernel::single(key($temp))->get_desc_tag();
               
                $productPromotion['goods'][$row['rule_id']]['tag'] = $productTag['name'];
                if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                    $productPromotion['goods'][$row['rule_id']]['use'] = 'false';
                }else{
                    $productPromotion['goods'][$row['rule_id']]['use'] = 'true';
                }
            }
        }
        
        //订单促销
        $giftCartObject = kernel::single('gift_cart_object_goods');
        // echo "<pre>";
        // var_dump($giftCartObject);
        foreach($goodsPromotion['order'] as $row){
          // var_dump($row);
            if(strpos($row['apply_platform'],'1') === false){
                continue;
            }
            if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                continue;
            }
            $temp = is_array($row['action_solution']) ? $row['action_solution'] : @unserialize($row['action_solution']);


            if(key($temp) == 'gift_promotion_solutions_gift'){
                $gain_gift = $temp['gift_promotion_solutions_gift']['gain_gift'];
                $giftId = array_merge($giftId,$gain_gift);
                if(!$giftCartObject->check_gift($giftId)){
                    continue;
                }
            }
            $productTag = kernel::single(key($row['action_solution']))->get_desc_tag();
            $productPromotion['order'][$row['rule_id']]['action_solution'] = $row['action_solution'];
            $productPromotion['order'][$row['rule_id']]['name'] = $row['name'];
            $productPromotion['order'][$row['rule_id']]['tag'] = $productTag['name'];
        }
        //赠品
        if($giftId){
            $giftRef = app::get('gift')->model('ref')->getList('*',array('product_id'=>$giftId,'marketable'=>'true'));
            if($giftRef){
                foreach($giftRef as $key=>$row){
                    if($row['marketable'] == 'false') continue;
                    if($row['cat_id']){
                        $giftCat = app::get('gift')->model('cat')->getList('*',array('cat_id'=>$row['cat_id']));
                        if($giftCat[0]['ifpub'] == 'false') continue;
                    }
                    $newGiftId[] = $row['product_id'];
                }
            }

            $aGift = app::get('b2c')->model('products')->getList('goods_id,product_id,name,store,freez',array('product_id'=>$newGiftId,'marketable='=>'true') );
            foreach($aGift as $key=>$row){
                $arrGoodsId[$key] = $row['goods_id'];
                if(is_null($row['store'])){
                    $aGift[$key]['store'] = 999999;
                }
            }
            $image = app::get('b2c')->model('goods')->getList('image_default_id,goods_id,nostore_sell,marketable',array('goods_id'=>$arrGoodsId) );
            $gift_image = array();
            foreach($image as $v){
                $gift_image[$v['goods_id']]=$v;
            }

            foreach($aGift as $key=>&$row){
                if($gift_image[$row['goods_id']]['marketable'] == 'false'){
                    unset($aGift[$key]);continue;
                }
                $row['image_default_id'] = $gift_image[$row['goods_id']]['image_default_id'];
                if($gift_image[$row['goods_id']]['nostore_sell']){
                    $row['store'] = 999999;
                }

            }
            $productPromotion['gift'] = $aGift;
        }
        // echo '<pre>';
        // var_dump($productPromotion);
        return $productPromotion;
    }
//add  end
    
    
  /*
        @mo
        根据促销规则，返回在促销条件过程中会员所购买该商品的数量(只包含促发了促销条件的个数)
     */
    public function get_number_from_rule_in_order($rule_protion)
    {   
           $member_id = kernel::single('b2c_user_object')->get_member_id();
            
            $db_order = app::get('b2c')->model('orders');

             $fromtime = $rule_protion['from_time'];
             $totime = $rule_protion['to_time'];

             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            $this_member_all_orders = $db_order->getList('order_id,member_id,createtime', $filter, 0, -1, 'order_id ASC');
        
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');
            //促发条件的 个数 $rule_protion['conditions']['conditions'][0]['value']
            
            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$rule_protion['conditions']['conditions'][0]['conditions'][0]['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods) && (int)$temp_goods[0]['nums'] >= $rule_protion['conditions']['conditions'][0]['value'])
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }
            }

            return  $order_goods_nums;
    }

/*
  判断当前 用户登陆，或者不属于这个办事处、或会员级别，返回false,代表任意一个都满足
 */
public function get_max_goods($promotion)
{
    $member_id = kernel::single('b2c_user_object')->get_member_id();
    if(empty($member_id)) return false;
                         
     $is_in_ofiice_memberlvid = $this->office_member_in($promotion,$member_id);
//      echo '<pre>';
            // var_dump($is_in_ofiice_memberlvid);
//             echo '===yyyyy===vvddd==vvv======ii';
     return $is_in_ofiice_memberlvid;
}
    /*
        是否可以加入购物车
        返回值：-1:该商品不存在满足的促销规则;0:存在但是超过了购买的限制数量;1:存在购买数量在限制范围内
        $productnumber:购物车中当前这个商品的个数
        productId:商品id productnumebr:购物车中该商品的数量 presentnumber:目前要加入购物车该商品的数量
     */
     public function canaddtocart($productId,$productnumber,$presentnumber)
    {
//     echo '<pre>';
//	var_dump('sssss');
//	echo '==-=-=-';
        $goods_ids = $this->get_good_id($productId);
              $goods_id = $goods_ids[0]['goods_id'];
          $promotions = $this->get_gift_of_full_promotion($goods_id);//该商品满赠促销的规则
            foreach ($promotions as $key => $value) {
               $promotion = $value;//默认情况该商品只有一个满足促销规则
            }
            //已经购买的个数          
            if(!empty($promotion))
            {
                

              $had_buy_this_goods_quantity = $this->get_number_from_rule_in_order($promotion);
               $now_can_buy_this_goods_quantity = $promotion['conditions']['conditions'][0]['maxquantity'] -$had_buy_this_goods_quantity;

               //@mo 2017年5月12日 10:25:38 

               if($now_can_buy_this_goods_quantity <= 0)
               {//用户之前购买的数量已满，接下来的下单都只能购买，促发的最大值-1个，避免促发促销规则
                //可以购买的个数
                $condition_value = (int)($promotion['conditions']['conditions'][0]['value'] - 1);
               //    echo '<pre>';
               // var_dump($condition_value);
               //  var_dump($presentnumber);
               // echo '---gg--------g';
                $now_can_buy_this_goods_quantity = $condition_value - $productnumber;
               
                if($now_can_buy_this_goods_quantity >0)
                  return $now_can_buy_this_goods_quantity;
                else
                  return 999999;//该商品购物车个数，已经促发条件的最大值-1；不允许继续添加到购物车
//                  return -2;//该商品购物车个数，已经促发条件的最大值-1；不允许继续添加到购物车
               }
               else
               {
                     //@mo
                if($now_can_buy_this_goods_quantity - $productnumber - $presentnumber >=0)
                    return $now_can_buy_this_goods_quantity - $productnumber - $presentnumber;//可以加入购物车，
               }
           

            }
        return -1;
    }

   /*
    @mo 2017年5月2日 13:55:09
    根据商品的product_id 返回在购物车中当前这个商品的个数
     */
    public function get_product_quantity_from_cart($product_id)
    {
        $cart = kernel::single('b2c_ctl_site_cart')->get_cart();
       
        foreach ($cart['object']['goods'] as $key => $value) {
            if($value['params']['product_id'] == $product_id)
                return $value['quantity'];
        }
        return 0;
    }

       /*
        返回可以加入购物车的个数 -1:不能加入 0:加入的个数为0 
     */
    public function can_buy_productid_quantity($productId)
    {
        $productnumber = $this->get_product_quantity_from_cart($productId);//该商品在购物车的数量

        $goods_ids = $this->get_good_id($productId);
              $goods_id = $goods_ids[0]['goods_id'];
          $promotions = $this->get_gift_of_full_promotion($goods_id);//该商品满赠促销的规则
 
         

            foreach ($promotions as $key => $value) {
               $promotion = $value;//默认情况该商品只有一个满足促销规则
            }
//            echo '<pre>';
//             var_dump($promotions);
//             echo '==============ii';
            //已经购买的个数          
            if(!empty($promotion))
            {
            
              $had_buy_this_goods_quantity = $this->get_number_from_rule_in_order($promotion);

               $now_can_buy_this_goods_quantity = $promotion['conditions']['conditions'][0]['maxquantity'] -$had_buy_this_goods_quantity;

            
               if($now_can_buy_this_goods_quantity <= 0)
               {
                //可以购买的个数
                $now_can_buy_this_goods_quantity = $promotion['conditions']['conditions'][0]['value'] - 1;
//                return $now_can_buy_this_goods_quantity;
                return 999999;
               }
                //@mo
               else
               {
                if($now_can_buy_this_goods_quantity - $productnumber >0)
                    return $now_can_buy_this_goods_quantity - $productnumber;//最后能加入购物车的数量 
                else
                    return 0;
               }
               //return $now_can_buy_this_goods_quantity;

            }
        return -1;
    }
      /*
        返回可以在购物车中（标签可以添加的最大值）的个数 -1:不能加入 
     */
    public function can_buy_productid_quantity_in_cart($productId)
    {
        $productnumber = $this->get_product_quantity_from_cart($productId);//该商品在购物车的数量

        $goods_ids = $this->get_good_id($productId);
              $goods_id = $goods_ids[0]['goods_id'];
          $promotions = $this->get_gift_of_full_promotion($goods_id);//该商品满赠促销的规则


       //  echo $goods_id.'<br><pre>';

 		//	var_dump($promotions);
            foreach ($promotions as $key => $value) {
               $promotion = $value;//默认情况该商品只有一个满足促销规则
            }
            

            
            
            //已经购买的个数          
            if(!empty($promotion))
            {
            	//echo '111111<br>';
              $had_buy_this_goods_quantity = $this->get_number_from_rule_in_order($promotion);


               $now_can_buy_this_goods_quantity = $promotion['conditions']['conditions'][0]['maxquantity'] -$had_buy_this_goods_quantity;
               
          
               if($now_can_buy_this_goods_quantity <= 0)
               {
            	//echo '2222222<br>';
                //可以购买的个数
                $now_can_buy_this_goods_quantity = $promotion['conditions']['conditions'][0]['value'] - 1;
               }
//               return 999999;
               return $now_can_buy_this_goods_quantity;

            }
            	
        return -1;
    }

    /*
      根据促销规则，判断当前用户是否属于这个办事处，和会员级别来决定是否能加入购物车或立即购买
     */
    public function office_member_in($promotion,$member_id)
    {
		
		foreach($promotion as $temp)
		{
			$promotion_1 = $temp;
		}
    // var_dump($promotion);
       $office_lv_ids = explode(',',$promotion_1['office_ids']);
       $member_lv_ids = explode(',',$promotion_1['member_lv_ids']);
      
      $member_one_id =  kernel::single('b2c_user_object')->get_member_lv($member_id);
      $office_one_id = $this->get_office_lv_id($member_id);
// 			echo '<pre>';
            // var_dump($member_id);
            // echo '<br>===yyyyy===$promotion==vvv======ii<br>';
            // var_dump($member_one_id);
            //  echo '<br>===yyyyy===vv$$member_one_id==vvv======ii<br>';
            //  var_dump($member_lv_ids);
            //  echo '<br>===yyyyy===vv$$member_lv_ids==vvv======ii<br>';
            //  var_dump($office_lv_ids);
            //  echo '<br>===yyyyy===$office_lv_ids==vvv======ii<br>';
            //    var_dump($office_one_id);
            //  echo '<br>===yyyyy===$office_one_idddd==vvv======ii<br>';

      //modified by lkb 去掉匹配办事处
      if(in_array($member_one_id,$member_lv_ids) )
      // if(in_array($member_one_id,$member_lv_ids) && in_array($office_one_id,$office_lv_ids))
        //modified end
       {
       	return true;
       }
       return false;

    }
    /*
      获取这个会员的办事处
     */
    public function get_office_lv_id($member_id)
    {
         $b2c_member_model=app::get('b2c')->model('members');
        $member_state=$b2c_member_model->getList('office_id',array('member_id'=>$member_id));
        return $member_state[0]['office_id'];
    }
    /*
        遍历购物车页面商品，设置购物车中商品的购买最大数量
     */
    public function set_good_cart(&$aCart)
    {
                 if(empty($aCart)) return 0;
                 $aCart['imo'] = 'uio';
      

        foreach ($aCart['object']['goods'] as $key => $value) {
        	
        	$product_id =$value['obj_items']['products'][0]['product_id'];
        	$giftperaddnum= $this->getstartgiftnum('product_id',$product_id);
        	
//        	$goods_ids = $this->get_good_id($value['obj_items']['products'][0]['product_id']);
//                    $goods_id = $goods_ids[0]['goods_id'];
//                        $promotions = $this->get_gift_of_full_promotion($goods_id);//该商品满赠促销的规则
//                    foreach ($promotions as $key => $value) {
//                       $promotion = $value;//默认情况该商品只有一个满足促销规则
//                    }
//                    $giftperaddnum=$promotion['conditions']['conditions'][0]['value'];
//        	echo $giftperaddnum;
        	
             
            $maxquantity = 0;
                $maxquantity = $this->can_buy_productid_quantity_in_cart($value['obj_items']['products'][0]['product_id']);


//echo '<br>';
//echo $maxquantity;
//echo '<br>';
              if( $maxquantity!= -1)
              {
//				$aCart['object']['gift']['order'][0]['quantity']=22;
//				$aCart['object']['goods'][0]['obj_items']['products'][0]['quantity']=2;
				
                 $aCart['object']['goods'][$key]['fullofgift']['maxbuygift'] = $maxquantity;
                 if($maxquantity < $giftperaddnum){
 
                    $aCart['object']['goods'][$key]['fullofgift']['maxbuygift'] = 999999;
				 }

                  $aCart['object']['goods'][$key]['fullofgift']['maxbuytype']  = app::get('b2c')->_('fullofgift');
              }
               
        }
             
       
    }
    //得到触发数量
   public function getstartgiftnum($type,$goods_ids){
    	//$value['obj_items']['products'][0]['product_id']
    	//两种id可能是goods_ids也可能是product_id
    	if($type=='product_id'){
    		$goods_ids = $this->get_good_id($goods_ids);
    	}
                    $goods_id = $goods_ids[0]['goods_id'];
                        $promotions = $this->get_gift_of_full_promotion($goods_id);//该商品满赠促销的规则
                    foreach ($promotions as $key => $value) {
                       $promotion = $value;//默认情况该商品只有一个满足促销规则
                    }
                    $giftperaddnum=$promotion['conditions']['conditions'][0]['value'];
			return $giftperaddnum;      	
    }
    
   

  

}
